package com.practice.designMode.responsibilityChain.validation;

import com.practice.designMode.responsibilityChain.exception.ValidatorException;

import java.util.ArrayList;
import java.util.List;

public class ValidatorChain {

    private final List<ValidatorHandler> validatorHandlers = new ArrayList<>();

    // 设置上下文，实现对整个责任链的控制
    // 实际思路 ： 设置一个变量作为一个信号量，提供处理接口和检验机制。处理器可以自行设置处理接口以获取对责任链的控制能力。
//    private final ValidatorContext validatorContext = new ValidatorContext();

    public void validate(Object bean) throws ValidatorException {
        ValidatorContext validatorContext = new ValidatorContext(bean);
        while (true){
            int i = validatorContext.CurrentIndex();
            if(i == validatorHandlers.size()){
                break;
            }
            validatorHandlers.get(i).validate(validatorContext.getValue(),validatorContext);
            if(validatorContext.shouldStop()){
                break;
            }
            if(i == validatorContext.CurrentIndex()){
                break;
            }
        }
        validatorContext.throwExceptionIfNecessary();
    }

    public void addValidatorHandler(ValidatorHandler validatorHandler) {
        validatorHandlers.add(validatorHandler);
    }
}
